import {Component, createRef} from "react";
import {Tabs} from "antd";

import Finished from "./Finished";
import Current from "./Current";

import LazyIcon from "../../components/Tools/Icon";

/**
 * Description: 展示历史记录的组件.
 * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-02-24 09:44:22
 */
class History extends Component<any, {
    createId: string | undefined,
    activeKey: string
}> {
    private readonly tab_key_current = 'current';
    private readonly tab_key_finished = 'finished';

    currentRef = createRef<Current>()
    finishedRef = createRef<Finished>()

    state = {
        createId: undefined,
        activeKey: 'current'
    }

    refresh = (createId: string, activeKey: string | undefined = undefined) => {
        this.setState({createId}, () => {
            if (activeKey) {
                this.setState({activeKey}, () => {
                    this.doRefresh(activeKey, createId)
                })
            } else {
                this.setState({activeKey: 'current'}, () => {
                    this.currentRef.current?.refresh(createId);
                })
            }
        })
    }

    render() {
        return (
            <>
                <Tabs activeKey={this.state.activeKey} defaultActiveKey={this.tab_key_current} onTabClick={(activeKey) => {
                    this.setState({activeKey}, () => {
                        this.doRefresh(activeKey, this.state.createId);
                    })
                }} items={[
                    {
                        label: <span><LazyIcon iconName="ClockCircleOutlined"/>正在进行</span>,
                        key: this.tab_key_current,
                        children: <Current ref={this.currentRef} embedded={this.state.createId != undefined}/>,
                        forceRender: true
                    },
                    {
                        label: <span><LazyIcon iconName="CheckCircleOutlined"/>已经完成</span>,
                        key: this.tab_key_finished,
                        children: <Finished ref={this.finishedRef} embedded={this.state.createId != undefined}/>,
                        forceRender: true
                    }
                ]}/>
            </>
        )
    }

    private doRefresh(activeKey: string, createId: string| undefined) {
        if (activeKey === this.tab_key_current) {
            createId ? this.currentRef.current?.refresh(createId) : this.currentRef.current?.handleFetch();
        }

        if (activeKey === 'finished') {
            createId ? this.finishedRef.current?.refresh(createId) : this.finishedRef.current?.handleFetch({instanceState: 1});
        }
    }
}

export default History;
